<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>断点续传</title>
</head>
<body>
<input type="file" id="file" onchange="upload(0)">
<progress id="progress" max="100" value="0"></progress>

<script type="text/javascript">
    // 文件切块大小为1MB
    const chunkSize = 1024*1024;

    // 从start字节处开始上传
    function upload(start) {
        let fileObj = document.getElementById('file').files[0];
        // 上传完成
        if (start >= fileObj.size) {
            return;
        }
        // 获取文件块的终止字节
        let end = (start + chunkSize > fileObj.size) ? fileObj.size : (start + chunkSize);
        // 将文件切块上传
        let fd = new FormData();
        fd.append('file', fileObj.slice(start, end));
        // POST表单数据
        let xhr = new XMLHttpRequest();
        xhr.open('post', 'http://localhost:2222/upload', true);
        xhr.onload = function() {
            if (this.readyState == 4 && this.status == 200) {
                // 上传一块完成后修改进度条信息，然后上传下一块
                let progress = document.getElementById('progress');
                progress.max = fileObj.size;
                progress.value = end;
                upload(end);
            }
        }
        xhr.send(fd);
    }
</script>
</body>
</html>